import React, { useEffect, useRef, useState } from 'react';
import Taro, { useRouter } from '@tarojs/taro';
import { useRequest } from 'ahooks';
import dayjs from 'dayjs';
import { Decimal } from 'decimal.js';
import { useInitStore } from '@/common/hox/initStore';
import { Loading } from '@/components';
import { useCityStore } from '@/common/hox/cityStore';
import { qsStringify } from '@/common/utils';
import { DateList, DateListRefType, EmptyCard } from '@/components';
import styles from './index.module.less';
import { useMovieStore } from '@/common/hox/movieStore';
import { usePageShow } from '@/common/hook/usePage';
import { getCinemaMovieList, getMovieCinemaScheduleList } from '@/service';
import { useUserStore } from '@/common/hox/userStore';
import appConfig from '@/utils/appConfig';
import { PageUrlMap } from '@/utils/enum';
import { PageUrlEnum } from '@/utils/enum';
import { CustomNavBar } from '@/components';
import { Location } from '@nutui/icons-react-taro';
import PhotoWall from './components/PhotoWall';
// router params
type RouterParamType = {
    movieId?: string;
    date?: string;
    cinemaId: string;
};

type TheaterListPagePropsType = {
    cinemaUrl?: string;
    movieId?: string;
    seatSelectUrl?: string;
    showCommission?: boolean;
};

const TheaterListPage = (props: TheaterListPagePropsType) => {
    const {
        cinemaUrl = PageUrlMap.get(PageUrlEnum.CinemaList),
        seatSelectUrl = PageUrlMap.get(PageUrlEnum.TheaterSeatSelect),
    } = props;
    const { params } = useRouter<RouterParamType>();
    const { initReady } = useInitStore();
    const { userInfo } = useUserStore();
    const { movieId: routerMovieId, cinemaId, date: defaultDate } = params || {};

    const {
        cinema: cinema,
        movie: { movieDetail, setMovieDetail },
        schedule: { setScheduleDetail },
        seat: { seatReset },
        combination: { combinationInfo },
    } = useMovieStore((store) => [
        store.cinema.cinemaInfo,
        store.movie.movieDetail,
        store.movie.setMovieDetail,
        store.schedule.setScheduleDetail,
        store.seat.seatReset,
        store.combination.combinationInfo,
    ]);

    const { movieLocation } = useCityStore();
    const cinemaInfo = cinema.cinemaInfo;
    const [movieId, setMovieId] = React.useState<number | string>();
    usePageShow(() => {
        // 未登录 跳转登录页面
        // 登录的但是未绑定手机号 跳转 绑定手机号页
        if (cinemaUrl && !cinemaInfo) {
            Taro.redirectTo({ 
                url: `${cinemaUrl}${routerMovieId ? `?movieId=${routerMovieId}` : ''}`
            });
        }
    });

    const [selectDate, setSelectDate] = useState<string>(defaultDate || '');
    const dataListRef = useRef<DateListRefType>(null);

    // 获取电影场次列表
    const getCinemaMovieListApi = useRequest(
        () => {
            if (combinationInfo)
                return getCinemaMovieList({
                    storeId: cinemaId,
                    couponCode: combinationInfo.couponCode,
                });
            return getCinemaMovieList({ storeId: cinemaId });
        },
        {
            ready: Boolean(cinemaId && initReady && userInfo?.userId),
            onSuccess: (res) => {
                if (res.list.length === 0) {
                    Taro.showModal({
                        title: '提示',
                        content: '当前影院没有电影场次，请选择其他影院或城市',
                        confirmText: '我知道了',
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                Taro.navigateBack();
                            } else if (res.cancel) {
                            }
                        },
                    });
                }
            },
        }
    );
    useEffect(() => {
        if (movieId && getCinemaMovieListApi.data?.list) {
            const res = getCinemaMovieListApi.data.list.find((item) => item.id === movieId);
            setMovieDetail(res);
        }
    }, [movieId, getCinemaMovieListApi.data]);

    // 获取电影院排片
    const getMovieCinemaScheduleListApi = useRequest(
        () =>
            getMovieCinemaScheduleList({
                storeId: cinemaId,
                movieShowTime: selectDate as string,
                filmId: movieId as number,
                cityId: movieLocation?.cityId,
            }),
        {
            ready: Boolean(movieId && selectDate && movieLocation?.cityId),
            refreshDeps: [movieId, selectDate],
        }
    );
    if (getCinemaMovieListApi.loading) return <Loading />;
    return (
        <div className={styles.page}>
            <CustomNavBar title={movieDetail?.name || cinemaInfo?.cinemaName || '电影'} />
            {/* 影院信息 */}
            {cinemaInfo && (
                <div
                    className={styles.cinemaInfo}
                    onClick={() => {
                        Taro.openLocation({
                            latitude: Number(cinemaInfo.latitude),
                            longitude: Number(cinemaInfo.longitude),
                            address: cinemaInfo.cinemaAddress,
                            name: cinemaInfo.cinemaName,
                            scale: 18,
                        });
                    }}
                >
                    <div
                        className={styles.textBox}
                        onClick={() => {
                            cinemaInfo.latitude !== null &&
                                Taro.openLocation({
                                    latitude: Number(cinemaInfo.latitude),
                                    longitude: Number(cinemaInfo.longitude),
                                    scale: 18,
                                });
                        }}
                    >
                        <div className={styles.name}>{cinemaInfo.cinemaName}</div>
                        <div className={styles.address}>
                            {cinemaInfo.cinemaAddress}
                            <Location color="var(--color-main)" className={styles.positionIcon} />
                        </div>
                    </div>
                </div>
            )}
            {/* 电影选择 滑动组件 */}
            <PhotoWall
                data={getCinemaMovieListApi.data?.list || []}
                defaultMovieId={routerMovieId}
                onMovieChange={setMovieId}
                useCombination={!!combinationInfo}
            />
            {/* 场次 日期 */}
            <div className={styles.searchWrapper}>
                {movieDetail && (
                    <DateList
                        ref={dataListRef}
                        data={movieDetail.showTimes}
                        value={selectDate}
                        prev="theater"
                        onChange={setSelectDate}
                    />
                )}
            </div>
            {!getMovieCinemaScheduleListApi.loading && (
                <div className={styles.content}>
                    {getMovieCinemaScheduleListApi.data?.list?.length === 0 ? (
                        <EmptyCard
                            selectDate={selectDate}
                            handleClick={() => dataListRef.current?.selectNext()}
                        />
                    ) : (
                        (getMovieCinemaScheduleListApi.data?.list || []).map((item) => {
                            const {
                                showId,
                                showTime,
                                duration,
                                showVersionType,
                                hallName,
                                originPrice,
                                isvId,
                                cinemaId,
                            } = item;
                            const salePrice = appConfig.movieConfig?.priceFormatter
                                ? appConfig.movieConfig.priceFormatter(item.salePrice)
                                : item.salePrice;
                            return (
                                <div
                                    className={styles.scheduleItem}
                                    key={showId}
                                    onClick={() => {
                                        setScheduleDetail(item);
                                        seatReset();
                                        const searchParams = qsStringify({
                                            movieId,
                                            isvId,
                                            showId,
                                            storeId: cinemaId,
                                        });
                                        seatSelectUrl &&
                                            Taro.navigateTo({
                                                url: `${seatSelectUrl}?${searchParams}`,
                                            });
                                    }}
                                >
                                    <div className={styles.timeBox}>
                                        <div className={styles.time}>
                                            {dayjs(showTime).format('HH:mm')}
                                        </div>
                                        {duration && duration > 0 ? (
                                            <div className={styles.timeOut}>
                                                {dayjs(showTime)
                                                    .add(duration, 'minutes')
                                                    .format('HH:mm分')}
                                                散场
                                            </div>
                                        ) : null}
                                    </div>
                                    <div className={styles.desc}>
                                        <div className={styles.showVersion}>{showVersionType}</div>
                                        <div className={styles.hallName}>{hallName}</div>
                                    </div>
                                    {combinationInfo ? (
                                        <div className={styles.price}>
                                            <div className={styles.cost}>
                                                <div>￥0</div>
                                                <div></div>
                                            </div>
                                        </div>
                                    ) : (
                                        <div className={styles.price}>
                                            {0 > 0 ? (
                                                // movieDetail?.couponShows.length || 0) > 0
                                                <>
                                                    <div className={styles.cost}>
                                                        <div>￥{originPrice}</div>
                                                        <div></div>
                                                    </div>
                                                </>
                                            ) : (
                                                <>
                                                    <div className={styles.cost}>
                                                        <div>￥{salePrice}</div>
                                                        <div>￥{originPrice}</div>
                                                    </div>
                                                    <div className={styles.saving}>
                                                        <div>省</div>
                                                        <div>
                                                            ￥
                                                            {Decimal.sub(
                                                                originPrice,
                                                                salePrice
                                                            ).toFixed(2)}
                                                        </div>
                                                    </div>
                                                </>
                                            )}
                                        </div>
                                    )}
                                    <div className={styles.action}>购票</div>
                                </div>
                            );
                        })
                    )}
                </div>
            )}
        </div>
    );
};
export default TheaterListPage;
